<template>
	<view class="file-wrap">
		<view ref="input" class="input"></view>
		<button class="cu-btn block bg-primary margin-tb-sm lg" @tap="uploadBtn">{{text}}</button>
	</view>
</template>

<script>
	import { VUE_APP_BASE_API } from '@/common/tools/config.js'
export default {
	props: {
		text: {
			type: String,
			default: '选择本地文件'
		},
		uploadfileUrl: {
			type: String,
			default: ''
		},
		limitsize: {
			type: Number,
			default: 5
		},
		formData: {
			type: Object,
			default: function () {
				return {}
			}
		},
		format: {
			type: String,
			default: 'application/pdf,application/vnd.ms-excel,application/msword'
		}
	},
	data() {
		return {
			//file文件
			fileinfo: {},
			filepaths: []
		};
	},
	computed: {
		size() {
			return this.limitsize * 1024 * 1024;
		}
	},
	// mounted 页面初始化的方法
	mounted() {
		var input = document.createElement('input');
		input.type = 'file';
		input.accept = this.format;
		input.style.display = 'none';
		input.id = 'file';
		input.onchange = event => {
			// 上传附件 获取文件信息
			this.fileinfo = event.target.files[0];
			this.upload();
		};
		this.$refs.input.$el.appendChild(input);
	},
	methods: {
		// 上传附件按钮 绑定file的点击事件
		uploadBtn() {
			return document.getElementById('file').click();
		},
		// 上传附件
		upload() {
			let fileinfo = this.fileinfo;
			console.info('此文件信息', fileinfo);
			// 校验文件大小
			if (fileinfo.size > this.size) {
				uni.showModal({
					title: '提示',
					showCancel: false,
					content: `仅支持文件大小小于等于${this.limitsize}M`
				})
				this.delfile();
				return;
			}
			var reader = new FileReader();
			reader.readAsDataURL(fileinfo);
			reader.onload = (e) => {
				this.uploadAPI(e)
			};
		},
		// 上传接口api
		uploadAPI(path) {
			this.filepaths.push(path);
			uni.uploadFile({
				url: VUE_APP_BASE_API,
				filePath: this.filepaths[0],
				name: 'file',
				formData: this.formData,
				success: e => {
					//上传成功
					this.$emit('confirm', e)
					console.log(e);
				},
				fail: e => {
					console.log(e);
					uni.redirectTo({
						url: '/print-pages/confirm?fileData='
					})
				}
			});
		},
		// 删除附件
		delfile() {
			//注意清空file,否则不能上传同一个文件
			document.getElementById('file').value = '';
		}
	}
};
</script>

<style>
.file {
	font-size: 32upx;
}

.filename {
	color: #808080;
}

.del {
	color: #0e90ce;
	float: right;
}

.btn {
	width: 100%;
	margin: 20upx 0;
	color: #007aff;
	background-color: #ffffff;
	border: #007aff 2upx solid;
}
</style>
